package xyz.bmj.view;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import org.jnativehook.keyboard.NativeKeyEvent;
import xyz.bmj.hotkey.Cbk;
import xyz.bmj.hotkey.HotKey;
import xyz.bmj.util.Constant;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ResourceBundle;

public class SettingCtr implements Initializable {
    public TextField play;
    public TextField prevMusic;
    public TextField nextMusic;
    public TextField volumeUp;
    public TextField volumeDown;

    private TextField[] fs;
    private Cbk[] cbks;


    public void OK(ActionEvent actionEvent) throws IOException {
        String hksJsonStr = JSONUtil.parse(MainView.hks).toStringPretty();
        System.out.println(hksJsonStr);
        FileUtil.writeString(hksJsonStr, getClass().getResource(Constant.SETTING_PATH).getPath(), StandardCharsets.UTF_8);
        MainView.mainScene.setRoot(MainView.root);
        HotKey.getInstance().clear();
        MainView.mainCtr.initHotKey();
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        fs = new TextField[]{play, prevMusic, nextMusic, volumeUp, volumeDown};
        cbks = new Cbk[]{MainView.hks.getPlay(), MainView.hks.getPrevMusic(), MainView.hks.getNextMusic(),
                MainView.hks.getVolumeUp(), MainView.hks.getVolumeDown()};
        for (int i = 0; i < fs.length; i++) {
            TextField field = fs[i];
            System.out.println(cbks[i]);
            field.setText(NativeKeyEvent.getModifiersText(cbks[i].markKey) + "+" + NativeKeyEvent.getKeyText(cbks[i].masterKey));
            int finalI = i;
            field.setOnKeyPressed(event -> {
                System.out.println(finalI);
                System.out.println(field.isFocused());
                keyCode(field, finalI);
            });
        }

    }

    private void keyCode(TextField field, int i) {
        HotKey hk = HotKey.getInstance();
        hk.setPress(nativeKeyEvent -> {
            if (!field.isFocused()) {
                return;
            }
            if (nativeKeyEvent.getModifiers() != 0) {
                String codeStr = NativeKeyEvent.getModifiersText(nativeKeyEvent.getModifiers());
                String kText = NativeKeyEvent.getKeyText(nativeKeyEvent.getKeyCode());
                if (kText.length() == 1 || kText.endsWith("箭头")) {
                    codeStr += "+" + kText;
                    cbks[i].masterKey = nativeKeyEvent.getKeyCode();
                    cbks[i].markKey = nativeKeyEvent.getModifiers();
                }
                fs[i].setText(codeStr);
            } else {
                fs[i].setText("");
            }
        });
    }
}
